<script setup>
import { ref } from 'vue'
import Modal from '@/components/Modal.vue'
import { addProjectAreaApi, updateProjectAreaApi } from '@/service'
import { message } from 'ant-design-vue'

const emit = defineEmits(['addCountry'])
const modalRef = ref()
const formRef = ref()
const formData = ref({
  project_area_name: '',
  project_area_state: null,
})

const rules = {
  project_area_name: [{ required: true, message: '请输入国家/地区名称' }],
  project_area_state: [{ required: true, message: '请选择所在洲' }],
}
const areaStateList = ref([
  {
    label: '美洲',
    value: 1,
  },
  {
    label: '欧洲',
    value: 2,
  },
  {
    label: '亚洲',
    value: 3,
  },
  {
    label: '非洲',
    value: 5,
  },
  {
    label: '大洋洲',
    value: 4,
  },
])

const submit = () => {
  formRef.value.validate().then(() => {
    if (formData.value.project_area_id) {
      updateProjectAreaApi(formData.value).then((res) => {
        message.success('编辑成功')
        emit('addCountry')
        close()
      })
    } else {
      addProjectAreaApi(formData.value).then((res) => {
        message.success('添加成功')
        emit('addCountry')
        close()
      })
    }
  })
}

const open = (params) => {
  if (params) {
    formData.value = params
  }
  modalRef.value.open()
}

const close = () => {
  formData.value = {
    project_area_name: '',
    project_area_state: null,
  }
  modalRef.value.close()
}

defineExpose({
  open,
  close,
})
</script>
<template>
  <Modal ref="modalRef" :title="formData?.id ? '编辑项目地区' : '创建项目地区'" @cancel="close">
    <a-form ref="formRef" :model="formData" :rules="rules" autocomplete="off">
      <a-form-item label="国家/地区" name="project_area_name">
        <a-input
          v-model:value="formData.project_area_name"
          placeholder="请输入国家/地区"
          show-count
          :maxlength="20"
        >
          <template #prefix> <AntdIcon icon="GlobalOutlined" /> </template>
        </a-input>
      </a-form-item>
      <a-form-item label="所在洲" name="project_area_state">
        <a-select
          v-model:value="formData.project_area_state"
          :options="areaStateList"
          placeholder="请选择所在洲"
        ></a-select>
      </a-form-item>
      <div class="flex justify-end gap-5">
        <a-button type="primary" @click="submit">提交</a-button>
        <a-button @click="close">取消</a-button>
      </div>
    </a-form>
  </Modal>
</template>
